package instances

import (
	"encoding/json"
	"fmt"
	apis2 "gluenet/pkg/apis"
	"gluenet/pkg/meta"
)

func DeleteInstance(ctx *apis2.GlueContext) {
	var (
		err  error
		key  string
		kind string
		mode string
	)
	key = ctx.WebContext.URLParam("guid")
	kind = ctx.WebContext.URLParam("kind")
	mode = ctx.WebContext.URLParam("mode")

	ctx.Logger.Debugf("revice delete instance %v %v %v", kind, mode, key)

	//获取instance
	var ins *meta.Instance
	if err = ctx.DataBase.InstanceGet(key, &ins); err != nil {
		ctx.Logger.Errorf("query error: %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("query error:%v", err), nil))
		return
	}

	//注销guid
	if err = unRegisterGuid(ctx, key); err != nil {
		ctx.Logger.Errorf("register guid %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("register gui %v", err), nil))
		return
	}

	//清楚调度结果
	if err = unScheduleReq(ctx, ins); err != nil {
		ctx.Logger.Errorf("shedule req %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("shedule req %v", err), nil))
		return
	}

	//删除数据
	if err = ctx.DataBase.InstanceDel(key); err != nil {
		ctx.Logger.Errorf("delete instance %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("delete instance %v", err), nil))
		return
	}

	ctx.WebContext.JSON(apis2.ResponseOK(nil))
}

func unRegisterGuid(ctx *apis2.GlueContext, data interface{}) error {
	var req = apis2.IRequest{Data: data}
	bts, _ := json.Marshal(req)
	_, err := ctx.Rpc.Request(apis2.GuidServiceUnRegister, bts)
	if err != nil {
		return err
	}

	return nil
}

func unScheduleReq(ctx *apis2.GlueContext, data interface{}) error {
	var req = apis2.IEvent{Data: data}
	bts, _ := json.Marshal(req)
	err := ctx.Rpc.Publish(apis2.SchedulerServiceUnSchedule, bts)
	if err != nil {
		return err
	}
	return nil
}
